package com.meitianhui.convenitenbuy.module.wallet.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.module.wallet.contract.WalletScanningStoreContract;
import com.meitianhui.convenitenbuy.module.wallet.di.DaggerWalletComponent;
import com.meitianhui.convenitenbuy.module.wallet.di.WalletModule;
import com.meitianhui.convenitenbuy.module.wallet.model.PayResultBean;
import com.meitianhui.convenitenbuy.module.wallet.model.StoreInfoBean;
import com.meitianhui.convenitenbuy.module.wallet.model.UsableChangeBean;
import com.meitianhui.convenitenbuy.module.wallet.presenter.WalletScanningStorePresenter;
import com.meitianhui.convenitenbuy.util.GlideUtils;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.dialog.PasswordDialog;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class WalletScanningStoreActivity extends BaseToolbarActivity implements WalletScanningStoreContract.View, PasswordDialog.OnDialogPsdCompleteListener {
    private StoreInfoBean bean;
    @Inject
    WalletScanningStorePresenter mPresenter;
    private TextView mTvTitle;
    private ImageView mIvImg;
    private TextView mTvAddress;
    private EditText mEtInput;
    private TextView mTvRemain;
    private Button mBtnConfirm;
    private PasswordDialog passwordDialog;
    private String storeId;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        bean = getIntent().getParcelableExtra(Constants.ARGUMENT);
        storeId = getIntent().getStringExtra("storeId");
        DaggerWalletComponent.builder().appComponent(App.getInstance().getAppComponent()).walletModule(new WalletModule(this)).build().inject(this);

        initId();
        initInfo();
        setTbTitle(getString(R.string.wallet_scanning_store));
        isEnable(false);
    }

    @Override
    protected int setView() {
        return R.layout.activity_wallet_scanning_store;
    }

    /**
     * 初始化Id
     */
    private void initId() {
        mTvTitle = getViewById(R.id.tv_wallet_scanning_store_title);
        mIvImg = getViewById(R.id.iv_wallet_scanning_store_img);
        mTvAddress = getViewById(R.id.tv_wallet_scanning_store_address);
        mEtInput = getViewById(R.id.et_wallet_scanning_store_input);
        mTvRemain = getViewById(R.id.tv_wallet_scanning_store_change);
        mBtnConfirm = getViewById(R.id.btn_wallet_scanning_store);
        registerPush();
        RxUtils.bindEvents(mBtnConfirm, this);
        mEtInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0, s.toString().indexOf(".") + 3);
                        mEtInput.setText(s);
                        mEtInput.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    mEtInput.setText(s);
                    mEtInput.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        mEtInput.setText(s.subSequence(0, 1));
                        mEtInput.setSelection(1);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void registerPush() {
        Disposable subscribe = RxBus.get().toFlowable(EventBean.class).subscribeOn(AndroidSchedulers.mainThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<EventBean>() {
            @Override
            public void accept(EventBean bean) throws Exception {
                if (bean != null) {
                    if (bean.type == Constants.EVENT_TYPE_REFRESH) {
                        mPresenter.getUsableChange();
                    }
                }
            }
        });
        mCompositeDisposable.add(subscribe);
    }

    /**
     * 初始化数据
     */
    private void initInfo() {
        mTvTitle.setText(getString(R.string.wallet_scanning_store_name) + bean.detail.getStores_name());
        mTvAddress.setText(bean.detail.getAddress());
        GlideUtils.setRectImage(this,bean.doc_url.get(bean.detail.getLogo_pic_path()), R.mipmap.wallet_scanning_store_default, R.mipmap.wallet_scanning_store_default, mIvImg);
        mPresenter.getUsableChange();
    }

    @Override
    public void call(View v) {
        super.call(v);
        switch (v.getId()) {
            case R.id.btn_wallet_scanning_store:
                mPresenter.checkInput(mEtInput.getText().toString().trim());
                break;
        }
    }

    @Override
    protected void onRefreshData() {
    }

    @Override
    public void showError(String msg) {

    }

    private void showPasswordDialog(String content) {
        passwordDialog = new PasswordDialog(this, R.layout.dialog_payment_pwd);
        passwordDialog.setOnDialogPsdCompareListener(this);
        passwordDialog.show();
//        passwordDialog.setPsdDescription(getString(R.string.dialog_password_function));
        passwordDialog.setPsdContent(content);
    }

    @Override
    public void onPasswordCorrect(PasswordDialog dialog) {
        mBtnConfirm.setEnabled(false);
        mPresenter.payFromStore(mEtInput.getText().toString(), storeId);
    }

    @Override
    public void onPasswordError(PasswordDialog dialog, String msg) {
        TipUtils.showToast(App.getInstance(), msg);
        passwordDialog.clearInput();
    }

    @Override
    public void getUsableBalanceBack(UsableChangeBean bean) {
        mTvRemain.setText((bean == null ? getString(R.string.wallet_zero_decimal)
                : (TextUtils.isEmpty(bean.getUsable_cash_balance()) ?
                        getString(R.string.wallet_zero_decimal) : bean.getUsable_cash_balance())));
    }

    @Override
    public void checkInputResult(int result) {
        switch (result) {
            case Constants.WALLET_PAYMENT_SETTING_ERROR:
                TipUtils.showToast(App.getInstance(), getString(R.string.wallet_payment_setting_error), 3);
                Intent intent = new Intent(this, WalletChangeRechargeActivity.class);
                intent.putExtra(Constants.ARGUMENT, mEtInput.getText().toString().trim());
                startActivity(intent);
                break;
            case Constants.WALLET_PAYMENT_SETTING_WRONG:
                TipUtils.showToast(App.getInstance(), getString(R.string.wallet_payment_setting_wrong), 3);
                mEtInput.setText("");
                break;
            case Constants.WALLET_PAYMENT_SETTING_EMPTY:
                TipUtils.showToast(App.getInstance(), getString(R.string.wallet_payment_setting_input), 3);
                mEtInput.setText("");
                break;
        }
    }

    @Override
    public void checkPassword(String content) {
        showPasswordDialog(content);
    }

    @Override
    public void checkResultSuccess(String string) {
        mBtnConfirm.setEnabled(false);
        mPresenter.payFromStore(mEtInput.getText().toString(), storeId);
    }

    @Override
    public void payResult(boolean result, String msg) {
        if (passwordDialog != null)
            passwordDialog.dismiss();
        if (result) {
            TipUtils.showToast(App.getInstance(), getString(R.string.wallet_change_recharge_success), 3);
            RxBus.get().post(new PayResultBean(Constants.PAY_RESULT_SUCCESS));
            finish();
        } else {
            TipUtils.showToast(App.getInstance(), msg);
            mBtnConfirm.setEnabled(true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}
